<template>
  <div class="foods-page">
    <div class="page-header">
      <n-button quaternary circle @click="$router.back()">
        <n-icon :size="20">
          <ArrowBack />
        </n-icon>
      </n-button>
      <h1>食物管理</h1>
      <n-button type="primary" @click="showCreateModal = true">
        <n-icon :size="16">
          <Add />
        </n-icon>
        添加食物
      </n-button>
    </div>
    
    <div class="page-content">
      <!-- 搜索和筛选 -->
      <n-card class="search-section">
        <div class="search-controls">
          <n-input
            v-model:value="searchKeyword"
            placeholder="搜索食物名称..."
            clearable
            @input="handleSearch"
          >
            <template #prefix>
              <n-icon :size="16">
                <Search />
              </n-icon>
            </template>
          </n-input>
          
          <n-select
            v-model:value="filterType"
            placeholder="筛选类型"
            clearable
            @update:value="handleFilter"
            :options="filterTypeOptions"
            style="width: 150px"
          />

          <n-select
            v-model:value="richInNutrients"
            placeholder="富含营养素"
            multiple
            clearable
            @update:value="handleFilter"
            :options="nutrientFilterOptions"
            style="width: 200px"
          />
        </div>
      </n-card>

      <!-- 系统预设食物 -->
      <n-card title="系统预设食物" class="foods-section">
        <div class="foods-list">
          <div
            v-for="food in systemFoods"
            :key="food.id"
            class="food-item"
          >
            <div class="food-info">
              <div class="food-header">
                <h3>{{ food.name_zh }}</h3>
                <span class="food-english">{{ food.name_en }}</span>
                <n-tag :color="{ color: '#f0f0f0', textColor: '#666' }" size="small">
                  系统预设
                </n-tag>
              </div>
              <div class="food-nutrients">
                <div class="nutrient-tags">
                  <n-tag v-if="food.protein_rich" type="success" size="small">富含蛋白质</n-tag>
                  <n-tag v-if="food.omega3_rich" type="info" size="small">富含Omega-3</n-tag>
                  <n-tag v-if="food.fiber_rich" type="warning" size="small">富含膳食纤维</n-tag>
                  <n-tag v-if="food.vitamin_c_rich" type="error" size="small">富含维生素C</n-tag>
                  <n-tag v-if="food.calcium_rich" type="default" size="small">富含钙</n-tag>
                  <n-tag v-if="food.iron_rich" type="primary" size="small">富含铁</n-tag>
                </div>
              </div>
              <div class="food-basic-info">
                <span v-if="food.energy_kcal">能量: {{ food.energy_kcal }}kcal/100g</span>
                <span v-if="food.protein_g">蛋白质: {{ food.protein_g }}g/100g</span>
                <span v-if="food.fat_g">脂肪: {{ food.fat_g }}g/100g</span>
                <span v-if="food.carb_g">碳水: {{ food.carb_g }}g/100g</span>
              </div>
            </div>
            <div class="food-actions">
              <n-button quaternary size="small" @click="viewFood(food as Food)">
                <n-icon :size="16">
                  <Eye />
                </n-icon>
              </n-button>
            </div>
          </div>
        </div>
      </n-card>

      <!-- 用户自定义食物 -->
      <n-card title="我的食物" class="foods-section">
        <div class="foods-list">
          <div
            v-for="food in userFoods"
            :key="food.id"
            class="food-item"
          >
            <div class="food-info">
              <div class="food-header">
                <h3>{{ food.name_zh }}</h3>
                <span class="food-english">{{ food.name_en }}</span>
                <n-tag :color="{ color: '#e6f7ff', textColor: '#1890ff' }" size="small">
                  自定义
                </n-tag>
              </div>
              <div class="food-nutrients">
                <div class="nutrient-tags">
                  <n-tag v-if="food.protein_rich" type="success" size="small">富含蛋白质</n-tag>
                  <n-tag v-if="food.omega3_rich" type="info" size="small">富含Omega-3</n-tag>
                  <n-tag v-if="food.fiber_rich" type="warning" size="small">富含膳食纤维</n-tag>
                  <n-tag v-if="food.vitamin_c_rich" type="error" size="small">富含维生素C</n-tag>
                  <n-tag v-if="food.calcium_rich" type="default" size="small">富含钙</n-tag>
                  <n-tag v-if="food.iron_rich" type="primary" size="small">富含铁</n-tag>
                </div>
              </div>
              <div class="food-basic-info">
                <span v-if="food.energy_kcal">能量: {{ food.energy_kcal }}kcal/100g</span>
                <span v-if="food.protein_g">蛋白质: {{ food.protein_g }}g/100g</span>
                <span v-if="food.fat_g">脂肪: {{ food.fat_g }}g/100g</span>
                <span v-if="food.carb_g">碳水: {{ food.carb_g }}g/100g</span>
              </div>
            </div>
            <div class="food-actions">
              <n-button quaternary size="small" @click="viewFood(food as Food)">
                <n-icon :size="16">
                  <Eye />
                </n-icon>
              </n-button>
              <n-button quaternary size="small" @click="editFood(food as Food)">
                <n-icon :size="16">
                  <Create />
                </n-icon>
              </n-button>
              <n-button quaternary size="small" type="error" @click="deleteFood(food as Food)">
                <n-icon :size="16">
                  <Trash />
                </n-icon>
              </n-button>
            </div>
          </div>
        </div>
        
        <n-empty v-if="userFoods.length === 0" description="暂无自定义食物">
          <template #extra>
            <n-button size="small" @click="showCreateModal = true">
              添加第一个食物
            </n-button>
          </template>
        </n-empty>
      </n-card>
    </div>

    <!-- 创建/编辑食物模态框 -->
    <n-modal
      v-model:show="showCreateModal"
      preset="card"
      :title="editingFood ? '编辑食物' : '添加食物'"
      style="width: 800px; max-height: 80vh;"
      :mask-closable="true"
      @esc="handleCancelFood"
    >
      <FoodForm
        :food="editingFood"
        :nutrients="nutrients"
        @submit="handleSubmitFood"
        @cancel="handleCancelFood"
      />
    </n-modal>

    <!-- 查看食物详情模态框 -->
    <n-modal
      v-model:show="showViewModal"
      preset="card"
      title="食物详情"
      style="width: 600px"
      :mask-closable="true"
      @after-leave="() => showViewModal = false"
      @esc="() => showViewModal = false"
    >
      <FoodDetail
        v-if="viewingFood"
        :food="viewingFood"
        :show-close-button="false"
      />
    </n-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import {
  ArrowBack,
  Add,
  Search,
  Eye,
  Create,
  Trash
} from '@vicons/ionicons5'
import { useFoodsStore } from '@/stores/foods'
import type { Food } from '@/types'
import FoodForm from '@/components/foods/FoodForm.vue'
import FoodDetail from '@/components/foods/FoodDetail.vue'

const foodsStore = useFoodsStore()

// 响应式数据
const showCreateModal = ref(false)
const showViewModal = ref(false)
const editingFood = ref<Food | null>(null)
const viewingFood = ref<Food | null>(null)
const searchKeyword = ref('')
const filterType = ref<string | null>(null)
const richInNutrients = ref<string[]>([])

// 计算属性
const systemFoods = computed(() => {
  return foodsStore.filteredFoods.filter(food => food.is_system)
})

const userFoods = computed(() => {
  return foodsStore.filteredFoods.filter(food => !food.is_system)
})

const nutrients = computed(() => foodsStore.nutrients)

const filterTypeOptions = [
  { label: '系统预设', value: 'system' },
  { label: '用户自定义', value: 'user' }
]

const nutrientFilterOptions = [
  { label: '蛋白质', value: 'protein' },
  { label: 'Omega-3', value: 'omega3' },
  { label: '膳食纤维', value: 'fiber' },
  { label: '维生素C', value: 'vitamin_c' },
  { label: '钙', value: 'calcium' },
  { label: '铁', value: 'iron' }
]

// 方法
const handleSearch = () => {
  updateSearchParams()
}

const handleFilter = () => {
  updateSearchParams()
}

const updateSearchParams = () => {
  const params: any = {}
  
  if (searchKeyword.value) {
    params.keyword = searchKeyword.value
  }
  
  if (filterType.value === 'system') {
    params.system_only = true
  } else if (filterType.value === 'user') {
    params.user_only = true
  }
  
  if (richInNutrients.value.length > 0) {
    params.rich_in = richInNutrients.value
  }
  
  foodsStore.searchParams = params
}

const viewFood = (food: Food) => {
  viewingFood.value = food
  showViewModal.value = true
}

const editFood = (food: Food) => {
  editingFood.value = food
  showCreateModal.value = true
}

const deleteFood = (food: Food) => {
  window.$dialog?.warning({
    title: '确认删除',
    content: `确定要删除食物"${food.name_zh}"吗？`,
    positiveText: '删除',
    negativeText: '取消',
    onPositiveClick: () => {
      // TODO: 实现删除逻辑
      window.$message?.success('删除成功')
    }
  })
}

const handleSubmitFood = async (formData: any) => {
  try {
    if (editingFood.value) {
      // TODO: 实现编辑逻辑
      window.$message?.success('编辑成功')
    } else {
      const result = await foodsStore.createFood(formData)
      if (!result) {
        return // 如果创建失败，不关闭模态框
      }
    }

    showCreateModal.value = false
    editingFood.value = null
  } catch (error) {
    console.error('Submit food error:', error)
    window.$message?.error('操作失败，请重试')
  }
}

const handleCancelFood = () => {
  showCreateModal.value = false
  editingFood.value = null
}

// 生命周期
onMounted(async () => {
  await Promise.all([
    foodsStore.fetchFoods(),
    foodsStore.fetchNutrients()
  ])
})
</script>

<style scoped>
.foods-page {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.page-header {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 24px;
  border-bottom: 1px solid #e0e0e0;
  background: white;
}

.page-header h1 {
  flex: 1;
  font-size: 24px;
  font-weight: 600;
  color: #333;
  margin: 0;
}

.page-content {
  flex: 1;
  padding: 24px;
  overflow-y: auto;
  background: #f5f5f5;
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.search-section {
  margin-bottom: 0;
}

.search-controls {
  display: flex;
  gap: 16px;
  align-items: center;
}

.search-controls .n-input {
  flex: 1;
}

.foods-section {
  margin-bottom: 0;
}

.foods-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.food-item {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  padding: 16px;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  background: white;
  transition: all 0.2s ease;
}

.food-item:hover {
  border-color: #1890ff;
  box-shadow: 0 2px 8px rgba(24, 144, 255, 0.1);
}

.food-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.food-header {
  display: flex;
  align-items: center;
  gap: 12px;
}

.food-header h3 {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin: 0;
}

.food-english {
  font-size: 14px;
  color: #666;
  font-style: italic;
}

.nutrient-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.food-basic-info {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  font-size: 14px;
  color: #666;
}

.food-actions {
  display: flex;
  gap: 8px;
  align-items: flex-start;
}

/* 移动端适配 */
@media (max-width: 768px) {
  .page-header {
    padding: 16px;
  }
  
  .page-content {
    padding: 16px;
  }
  
  .search-controls {
    flex-direction: column;
    align-items: stretch;
  }
  
  .food-item {
    flex-direction: column;
    gap: 12px;
  }
  
  .food-actions {
    align-self: flex-end;
  }
  
  .food-header {
    flex-wrap: wrap;
  }
  
  .food-basic-info {
    flex-direction: column;
    gap: 4px;
  }
}
</style>
